#import "SongsSingleton.h"

@interface SongsSingleton ()

@property NSMutableArray* favoritesSongs;
@property NSArray* allSongs;
@property NSMutableArray* allNotes;


@end

@implementation SongsSingleton

static BOOL isInited=NO;
+(id)sharedSongsSingleton{
    static SongsSingleton* p=nil;
    if(p==nil)
        p=[[super alloc]init];
    return p;
}

+(id)alloc {
    return [SongsSingleton sharedSongsSingleton];
}

-(id)copy {
    return [SongsSingleton sharedSongsSingleton];
}

-(id)mutableCopy {
    return [SongsSingleton sharedSongsSingleton];
}

- (instancetype)init
{
    if (isInited){
        return  self;
    }
    
    self = [super init];
    if (self) {
        isInited=YES;
        self.allSongs=[[NSMutableArray alloc]init];
        self.favoritesSongs=[[NSMutableArray alloc]init];
        isInited=YES;
    }
    return self;
}
-(void)notesFromFile:(NSString*)fileName {
    NSArray* allNotes=[[NSMutableArray alloc]init];
    NSString* filePath = fileName;
    NSString* fileRoot = [[NSBundle mainBundle]
                          pathForResource:filePath ofType:@"txt"];
    
    
    NSString* fileContents =
    [NSString stringWithContentsOfFile:fileRoot
                              encoding:NSUTF8StringEncoding error:nil];
    
    // first, separate by new line
    allNotes = [fileContents componentsSeparatedByCharactersInSet:
                [NSCharacterSet newlineCharacterSet]];
    for(NSInteger index = 0;index<[allNotes count];index++){
        
        self.allNotes=[[NSMutableArray alloc]initWithArray:allNotes];
    }
    
    
}
-(NSInteger)numberOfNotesInAllSongs{
    return  [self.allSongs count];
}
-(NSInteger)numberOfNotesInFavoriteSongs{
    return [self.favoritesSongs count];
}
-(BOOL)isFavoriteSongWithIndex:(NSInteger) index{
   return  [self.favoritesSongs containsObject:[self.allSongs objectAtIndex:index]];
}
-(void)addToFavoritesSongWithIndex:(NSInteger) index{
    if(![self.favoritesSongs containsObject:[self.allSongs objectAtIndex:index]]){
    [self.favoritesSongs addObject:[self.allSongs objectAtIndex:index]];
    NSFetchRequest* fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Song"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"songName==%@",[[self.allSongs objectAtIndex:index] songName] ];
    [fetchRequest setPredicate:predicate];
    Song* currSong=[[self.managedObjectContext executeFetchRequest:fetchRequest error:nil] objectAtIndex:0];
    currSong.favorites=[NSNumber numberWithBool:YES];
    [self saveContext];
    }
    
}
-(void)removeFromFavoritesSongWithIndex:(NSInteger)index{
    if([self.favoritesSongs containsObject:[self.allSongs objectAtIndex:index]]){
    [self.favoritesSongs removeObject:[self.allSongs objectAtIndex:index]];
    NSFetchRequest* fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Song"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"songName==%@",[[self.allSongs objectAtIndex:index] songName] ];
    [fetchRequest setPredicate:predicate];
    Song* currSong=[[self.managedObjectContext executeFetchRequest:fetchRequest error:nil] objectAtIndex:0];
    currSong.favorites=[NSNumber numberWithBool:NO];
    [self saveContext];
     }
   
}

-(BOOL)isEmptyCoreDate{
    
    
    NSFetchRequest* fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Song"];
    self.allSongs=[self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    if([self.allSongs count]==0){
//        NSLog(@"%d",[self.allSongs count]);
        return NO;
    }
    return YES;
}

-(void)deleteCoreData{
    NSFetchRequest* fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Song"];
    self.allSongs=[self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    for(Song* currentSong in self.allSongs){
        [self.managedObjectContext deleteObject:currentSong];
        [self saveContext];
    }
    
}


-(void)fillCoreData{
    if(![self isEmptyCoreDate]){
        
        [self notesFromFile:@"stairway"];
        Song* stairway=[NSEntityDescription insertNewObjectForEntityForName:@"Song" inManagedObjectContext:self.managedObjectContext];
        stairway.author=@"Led Zepelin";
        stairway.favorites=[NSNumber numberWithBool:NO];
        stairway.songName=@"Stairway to heaven";
        NSMutableArray* stringNotes=[[NSMutableArray alloc]init];
        for(NSInteger stringIndex=0;stringIndex <6 ;stringIndex++){
            [stringNotes addObject:[NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:self.managedObjectContext]];
            [[stringNotes objectAtIndex:stringIndex] setNotesString:[self.allNotes objectAtIndex:stringIndex ]];
        }
        stairway.notes =[NSOrderedSet orderedSetWithArray:stringNotes];
        
        [self notesFromFile:@"connon"];
        Song* canon=[NSEntityDescription insertNewObjectForEntityForName:@"Song" inManagedObjectContext:self.managedObjectContext];
        canon.author=@"Pachelbel";
        canon.favorites=[NSNumber numberWithBool:NO];
        canon.songName=@"Canon in D";
        [stringNotes removeAllObjects];
        for(NSInteger stringIndex=0;stringIndex <6 ;stringIndex++){
            [stringNotes addObject:[NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:self.managedObjectContext]];
            [[stringNotes objectAtIndex:stringIndex] setNotesString:[self.allNotes objectAtIndex:stringIndex ]];
        }
        canon.notes =[NSOrderedSet orderedSetWithArray:stringNotes];
        
        
        [self notesFromFile:@"jinglebells"];
        Song* jingle=[NSEntityDescription insertNewObjectForEntityForName:@"Song" inManagedObjectContext:self.managedObjectContext];
        jingle.author=@"Christmas song";
        jingle.favorites=[NSNumber numberWithBool:NO];
        jingle.songName=@"Jingle Bells";
        [stringNotes removeAllObjects];
        for(NSInteger stringIndex=0;stringIndex <6 ;stringIndex++){
            [stringNotes addObject:[NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:self.managedObjectContext]];
            [[stringNotes objectAtIndex:stringIndex] setNotesString:[self.allNotes objectAtIndex:stringIndex ]];
        }
        jingle.notes =[NSOrderedSet orderedSetWithArray:stringNotes];
        
        [self notesFromFile:@"sweet"];
         Song* sweet=[NSEntityDescription insertNewObjectForEntityForName:@"Song" inManagedObjectContext:self.managedObjectContext];
        sweet.author=@"Metallica";
        sweet.favorites=[NSNumber numberWithBool:NO];
        sweet.songName=@"Nothing else matters";
        [stringNotes removeAllObjects];
        for(NSInteger stringIndex=0;stringIndex <6 ;stringIndex++){
            [stringNotes addObject:[NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:self.managedObjectContext]];
            [[stringNotes objectAtIndex:stringIndex] setNotesString:[self.allNotes objectAtIndex:stringIndex ]];
        }
        sweet.notes =[NSOrderedSet orderedSetWithArray:stringNotes];
        [self saveContext];
    }
    else{
//        NSLog(@"NOT EMPTY CORE DATA");
    }
}

-(void)fetchData{
    
    NSFetchRequest* fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Song"];
    self.allSongs=[self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    for(Song* currentSong in self.allSongs){
       // [self.managedObjectContext deleteObject:currentSong];
        
                if([currentSong.favorites boolValue]==TRUE){
                    [self.favoritesSongs addObject:currentSong];
                }
    }
}

-(Song*)songForIndex:(NSInteger)index{
    return [self.allSongs objectAtIndex:index];
}
-(Song*)favoriteSongForIndex:(NSInteger)index{
    return [self.favoritesSongs objectAtIndex:index];
}

-(NSInteger)numberOfRowsAllSongs{
    return [self.allSongs count];
}
-(NSInteger)numberOfRowsFavoritesSongs{
    return [self.favoritesSongs count];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "IOTC.CoreDataDemo1" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"GuitarPlayingApp" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"GuitarPlayingApp.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}







@end
